package com.app.newcsc.activity;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.databinding.ActivityTabBarBinding;
import com.app.newcsc.entity.Message;
import com.app.newcsc.fragment.main.FundFragment;
import com.app.newcsc.fragment.main.MarketFragment;
import com.app.newcsc.fragment.main.MyFragment;
import com.app.newcsc.fragment.main.TransactionFragment;
import com.app.newcsc.utils.PermissionUtils;
import com.app.newcsc.utils.SpUtils;
import com.app.newcsc.utils.ToastUtils;
import com.app.newcsc.utils.Utils;
import com.app.newcsc.view.AuthorizationDialog;
import java.util.ArrayList;
import java.util.List;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.bus.RxBus;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

public class MainActivity extends BaseActivity<ActivityTabBarBinding, BaseViewModel> {

    private List<Fragment> mFragments;
    private NavigationController navigationController;
    private MarketFragment marketFragment;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_tab_bar;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
//    private Disposable mSubscription;
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        if(mSubscription != null)
//        {
//            RxSubscriptions.remove(mSubscription);
//        }
//    }

    @Override
    public void initData() {
//        mSubscription = RxBus.getDefault().toObservable(Message.class)
//                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
//                .subscribe(new Consumer<Message>() {
//                    @Override
//                    public void accept(final Message message) throws Exception {
//                        Log.e("TAG","=======MainActivity========message=============="+message.getName());
//                        if(message.getName().equals("start_login"))
//                        {
//                            navigationController.setSelect(3);
//                            commitAllowingStateLoss(3);
//                        }
//                    }
//                });
//        //将订阅者加入管理站
//        RxSubscriptions.add(mSubscription);


        //初始化底部Button
        initBottomTab();

        //初始化Fragment
        initFragment();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (!TextUtils.isEmpty(SpUtils.get(this, "ai_apptag"))
                && !TextUtils.isEmpty(SpUtils.get(this, "ai_code"))
                && !TextUtils.isEmpty(SpUtils.get(this, "ai_name")) && isFastClick()) {
            AuthorizationDialog dialog = new AuthorizationDialog(this);
            dialog.show(v -> {
//                sendData();
                if (!TextUtils.isEmpty(SpUtils.get(this, "ai_type"))) {
//                    getshoptoken();
                } else {
//                    sendData();
                }
                dialog.dismiss();
            });
            dialog.cancel(v -> {
                dialog.dismiss();
//                goCSC(0);
            });
        }
    }

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 2000;
    private static long lastClickTime;

    public boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;

//        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        SpUtils.put(this,"isLogin","1");
//        statusBarTransparent();
//        Log.e("TAG", "=====123123====onCreate====================");
//        Intent intent = getIntent();
//        if(intent != null)
//        {
//            Log.e("TAG", "=========onCreate============intent========");
//            if(intent.hasExtra("token"))
//            {
//                Log.e("TAG", "=========onCreate============token========"+intent.getStringExtra("token"));
//            }
//        }
//        Log.e("TAG", "=====123123====onCreate====MainActivity====1111====token========"+getIntent().getStringExtra("token"));
//        getToken(getIntent());
        PermissionUtils.with(this)
                .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .addPermission(Manifest.permission.CAMERA)
//                .addPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
//                .addPermission(Manifest.permission.ACCESS_FINE_LOCATION)
//                .addPermission(Manifest.permission.READ_PHONE_STATE)
                .initPermission().size();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();//如果为true，则表示屏幕“亮”了，否则屏幕“暗”了。
        if (isScreenOn) {
            String isLogin = SpUtils.get(this, "isLogin");
            if (!isLogin.equals("1")) {
                finish();
            }
        }

    }

    //    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        setIntent(intent);
//        if(intent != null)
//        {
//            if(intent.hasExtra("token"))
//            {
//                Log.e("TAG", "=====123123====onNewIntent============token========"+intent.getStringExtra("token"));
//                ShareUtil.getInstance().save(ShareUtil.ACCESS_TOKEN,intent.getStringExtra("token"));
//                RxBus.getDefault().post(new Message("start_login",""));
//            }
//        }
//    }
//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        Log.e("TAG", "=====123123====onNewIntent====MainActivity====1111====token========"+intent.getStringExtra("token"));
//        setIntent(intent);
//        getToken(intent);
//    }
//    private void getToken(Intent intent)
//    {
//        if(intent != null)
//        {
//            Log.e("TAG", "=====123123====getToken=====2222====MainActivity===token========"+intent.getStringExtra("token"));
//            if(intent.hasExtra("token"))
//            {
//                Log.e("TAG", "=====123123====getToken=====3333====MainActivity===token========"+intent.getStringExtra("token"));
//                ShareUtil.getInstance().save(ShareUtil.ACCESS_TOKEN,intent.getStringExtra("token"));
//                RxBus.getDefault().post(new Message("start_login",""));
////                isGetToken = true;
//            }
//        }
//    }

    @Override
    public void onCreatePre() {
        super.onCreatePre();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.BLACK);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    @Override
    public void onCreateAfter() {
        super.onCreateAfter();
        setWhiteStatusBar(true);
    }

    private void initFragment() {
        marketFragment = new MarketFragment();
        mFragments = new ArrayList<>();
        mFragments.add(marketFragment);
        mFragments.add(new TransactionFragment());
        mFragments.add(new FundFragment());
//        mFragments.add(new OrderFragment());
        mFragments.add(new MyFragment());
//        if(getIntent() != null && getIntent().hasExtra("isGetToken")&& getIntent().getBooleanExtra("isGetToken",false))
//        {
//            if(navigationController != null)
//            {
////                commitAllowingStateLoss(3);
////                navigationController.setSelect(3);
////                navigationController.
//            }
//        }
//        else
//        {
//            //默认选中第一个
//            commitAllowingStateLoss(0);
//        }

        //默认选中第一个
        commitAllowingStateLoss(0);
    }

    private void initBottomTab() {
        navigationController = binding.pagerBottomTab.material()
                .addItem(R.mipmap.shichang, R.mipmap.shichang_select, "市场", ContextCompat.getColor(this, R.color.my_color_3212CF))
                .addItem(R.mipmap.jiaoyi, R.mipmap.jiaoyi_select, "交易", ContextCompat.getColor(this, R.color.my_color_3212CF))
                .addItem(R.mipmap.zichan, R.mipmap.zichan_select, "资产", ContextCompat.getColor(this, R.color.my_color_3212CF))
//                .addItem(R.mipmap.wode_select,R.mipmap.yingyong, "订单详情",ContextCompat.getColor(this,R.color.colorAccent))
                .addItem(R.mipmap.my, R.mipmap.my_select, "我的", ContextCompat.getColor(this, R.color.my_color_3212CF))
                .setDefaultColor(ContextCompat.getColor(this, R.color.my_color_939393))//textColorVice
                .build();
        //底部按钮的点击事件监听
        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
//                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//                transaction.replace(R.id.frameLayout, mFragments.get(index));
//                transaction.commitAllowingStateLoss();
                if (index == 2) {
                    if (!Utils.isLogin()) {
                        navigationController.setSelect(old);
                        return;
                    }
                }
                commitAllowingStateLoss(index);

                RxBus.getDefault().post(new Message("MainActivity_index_" + index, ""));
            }

            @Override
            public void onRepeat(int index) {
            }
        });
    }

    private void commitAllowingStateLoss(int position) {
        hideAllFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(position + "");
        if (currentFragment != null) {
            transaction.show(currentFragment);
        } else {
            currentFragment = mFragments.get(position);
            transaction.add(R.id.frameLayout, currentFragment, position + "");
        }
        transaction.commitAllowingStateLoss();
    }

    //隐藏所有Fragment
    private void hideAllFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mFragments.size(); i++) {
            Fragment currentFragment = getSupportFragmentManager().findFragmentByTag(i + "");
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
        }
        transaction.commitAllowingStateLoss();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private long exitTime;

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtils.toastLong(getResources().getString(R.string.string_exit_warn));
            exitTime = System.currentTimeMillis();
        } else {
            AppManager.getAppManager().finishAllActivity();
        }

    }
}